<?php


namespace App\Services;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class TtMiniAppService
{
    protected $client;
    protected $config;
    protected $access_token;

    public function __construct()
    {
        $this->config = [
            'app_id' => config('account.ttapp.app_id'),
            'secret' => config('account.ttapp.secret'),
        ];
        $this->client = new Client([
            'base_uri' => 'https://developer.toutiao.com',
            'timeout' => 10.0,
        ]);
    }

    /**
     * @param $js_code
     * @return mixed
     * 获取openid
     */
    public function code2Session($js_code)
    {
        $response = $this->client->get('api/apps/jscode2session', [
            'query' => [
                'appid' => $this->config['app_id'],
                'secret' => $this->config['secret'],
                'code' => $js_code
            ]
        ]);

        $arr = $response->getBody()->getContents();
        return json_decode($arr, true);
    }

    public function getAccessToken()
    {
        if (!$this->access_token) {
            $this->access_token = Cache::get('tt_access_token', null);
            if (!$this->access_token) {

                $response = $this->client->get('api/apps/token', [
                    'query' => [
                        'appid' => $this->config['app_id'],
                        'secret' => $this->config['secret'],
                        'grant_type' => 'client_credential'
                    ]
                ]);

                $arr = $response->getBody()->getContents();
                $arr = json_decode($arr, true);
                $this->access_token = $arr['access_token'];
                Log::info('头条 access_token 返回', ['data' => $arr]);
                Cache::put('tt_access_token', $arr['access_token'], $arr['expires_in']);
            }
        }
        return $this->access_token;
    }
}
